import { cline, obj_str, CurModel } from 'sui';
import { put_log } from 'base/ctl/log';

const json_data = (data) => {
    return {
        method: 'POST',
        body: JSON.stringify(data),
        headers: {
            'Content-Type': 'application/json'
        }
    };
};

const send_json = (url, data, okfun=null, errfun=null, fnDone=null) => {
    fetch(url, json_data(data))
        .then(res => {
            if (res.ok) {
                return res.json();
            }

            throw new Error('err');
        })
        .then(
            r => {
                const data = r["data"];
                const code = r["code"];
                const message = r["message"];

                if (code === 1000) {
                    if (okfun) {
                        okfun(data);
                    }
                }
                else {
                    if (errfun) {
                        errfun(message);
                    }
                }

                if (fnDone) {
                    fnDone();
                }
            },
            e => {
                if (errfun) {
                    errfun(e);
                }

                if (fnDone) {
                    fnDone();
                }
            }
        )
        .catch(e => {
            console.log(`error: ${e}`);
        });
};

const getUrl = (v) => {
    const host = window.location.host;

    let pos = host.indexOf(":8088");
    if (pos > 0) {
        return "http://" + window.location.hostname + v;
    }

    pos = host.indexOf(":9000");
    if (pos > 0) {
        return "http://" + window.location.hostname + v;
    }

    return "http://" + window.location.host + v;
};

const is_debug = () => {
    if (process.env.NODE_ENV !== 'production') {
        return true;
    }

    return false;
};

const get_way = (url, port, mod) => {
    const t = is_debug() ? `http://127.0.0.1:${port}/${mod}` : getUrl(`/${mod}`);
    if (url) {
        return t + "/" + url;
    }

    return t;
};

class GateWay {
    static is_debug() {
        return is_debug();
    }

    static url_xlsx() {
        return get_way("xlsx", 9982, "file");
    }

    static url_esop() {
        return get_way("esop", 9982, "file");
    }

    static url_file() {
        return get_way("", 9982, "file");
    }

    static url_upload() {
        return get_way("upload", 9982, "file");
    }

    static getCfg() {
        return GateWay.is_debug() ? "http://127.0.0.1:9998/cfg/get" : getUrl("/cfg/get");
    }

    static urlFileCmd(url) {
        const t = GateWay.is_debug() ? "http://127.0.0.1:9992/filecmd" : getUrl("/filecmd");
        return t + url;
    }

    static getUpload() {
        return GateWay.is_debug() ? "http://127.0.0.1:9991/upload" : getUrl("/upload");
    }

    static getFile() {
        return GateWay.is_debug() ? "http://127.0.0.1:9997/file" : getUrl("/file");
    }
}

const scan_db = (data) => {
    let tab = obj_str(data, "n");
    if (!tab) {
        tab = obj_str(data, "tab");
    }

    if (tab) {
        const db = CurModel.get_db(tab);
        if (db) {
            data["db"] = db;
        }
    }

    return data;
};

const uDb = (fnDone, url, data, okfun=null, errfun=null) => send_json(get_way(url, 9981, "cfgdb"), data, okfun, errfun, fnDone);

const uFile = (fnDone, url, data, okfun=null, errfun=null) => send_json(get_way(url, 9982, "file"), data, okfun, errfun, fnDone);

const urlTb = (fnDone, url, data, okfun=null, errfun=null) => {
    const cmd = scan_db(data);
    send_json(get_way(url, 9983, "timedb"), cmd, okfun, errfun, fnDone);
};

const uReal = (fnDone, url, data, okfun=null, errfun=null) => send_json(get_way(url, 9984, "real"), data, okfun, errfun, fnDone);

const uJob = (fnDone, url, data, okfun=null, errfun=null) => send_json(get_way(url, 9987, "job"), data, okfun, errfun, fnDone);

const uPlc = (fnDone, url, data, okfun=null, errfun=null) => send_json(get_way(url, 9985, "plc"), data, okfun, errfun, fnDone);

const uXls = (fnDone, url, data, okfun=null, errfun=null) => send_json(get_way(url, 9986, "xls"), data, okfun, errfun, fnDone);

const uPrint = (fnDone, data, okfun=null, errfun=null, log=true) => {
    const url = "http://127.0.0.1:9000/api/device";

    put_log(url, data, "打印");

    if (log) {
        const cmd = {
            tab: "printlog",
            line: cline(),
            que: true,
            data: [{
                psn: obj_str(data, "sn"),
                wsn: "stock",
                v: data,
            }]
        };

        urlTb(null, "chunk", cmd);
    }

    send_json(url, data, okfun, errfun, fnDone);
};

export {uJob, uXls, uPrint, uPlc, GateWay, urlTb, uReal, uFile, uDb};
